package musicchange;

import java.io.File;
import java.io.IOException;

import main.FileOperations;
import main.FinishWindow;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;

import exceptions.NotDirException;

public class Metadata {
	File dir;

	public Metadata(String path) {
		try {
			dir = FileOperations.checkDir(path);
			boolean end = tagger();
			System.out.println("State of tagging: " + end);
			if(end){
				FinishWindow.main(null);
			}
		} catch (NotDirException e) {
			System.out.println(e.getStackTrace());
		}
	}

	private boolean tagger() {
		File[] list = dir.listFiles();
		for (int i = 0; i < list.length; i++) {
			if (list[i].isDirectory()) {
				File[] listIn = list[i].listFiles();
				for (int j = 0; j < listIn.length; j++){
					
					if (listIn[j].isFile()) {
						System.out.println("katalog: " + list[i] + ", plik; " + listIn[j].getName());
						giveTag(listIn[j]);
					}
				}
			}
			if (list[i].isFile()) {
				giveTag(list[i]);
			}
		}

		return true;
	}

	private void giveTag(File f) {
		AudioFile audio;
		Tag tag;
		String title, artist;
		try {
			audio = AudioFileIO.read(f);
			tag = audio.getTag();
			artist = f.getName().split(" - ")[0];
			title = f.getName().split(" - ")[1];
			title = title.substring(0, title.length() - 4);
			System.out.println(artist);
			System.out.println(title);
			tag.setField(FieldKey.ARTIST, artist + "dziala w srodku");
			tag.setField(FieldKey.TITLE, title);
			AudioFileIO.write(audio);
		} catch (CannotReadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TagException e) {
			e.printStackTrace();
		} catch (ReadOnlyFileException e) {
			e.printStackTrace();
		} catch (InvalidAudioFrameException e) {
			e.printStackTrace();
		} catch (CannotWriteException e) {
			e.printStackTrace();
		}
	}

}
